<template>
  <div class="">
    <template v-for="(item, index) in productList">
    <div class="activity-item">
      <span class="discount-card" v-if="item.personalLimited">人均限购{{item.personalLimitNum}}件</span>
      <div class="sell-out" v-if="item.stock < 1">
        <img class="sell-out-img" src="../../images/sellnull.png" />
      </div>
      <div class="pointer activity-left" @click="openDetail(item)">
        <div class="preview-img">
          <img class="img" :src="prefixImg + item.image"/>
        </div>
      </div>
      <div class="price-box activity-right">
        <div class="pro-info txt-lf" @click="openDetail(item)">
          <h3 class="pro-name ellipsis">{{item.goodsName}} {{item.brandName}}</h3>
          <h4 class="pro-type">{{item.standard}}</h4>
        </div>
        <div class="price">
          <template v-if="loginStatus === 1">
            <span class="now" v-if="fielsStatus !== 0">￥{{item.pmtPrice | floatPrices}}</span>
            <span class="now" v-else>??.??</span>
            <span class="old">￥{{item.price | floatPrices}}</span>
          </template>
          <p class="txt-center ft-14" v-else-if="loginStatus === 4">登录后查看价格</p>
          <p class="txt-center ft-14" v-else>审核通过可查看</p>
        </div>
        <div class="activity-number">
          <span class="left">剩{{item.stock}}件</span>
          <!-- numList[index] -->
          <el-input-number class="input-num-self-activity"
            v-if="fielsStatus === 1"
            :title="`包装数${item.packingNum}`"
            size="mini"
            @keydown.110.native.prevent="" 
            v-model="numList[index]"
            :min="0"
            :max="item.stockLimit ? (item.personalLimited ? item.lastPersonalLimitNum : item.stock) : 99999"
            :step="item.packingNum"
            :ref="`pro_${index}`"
            @change="debounceChangeProNum($event, index, item.packingNum, item)" >
          </el-input-number>
        </div>
          
        <!-- :disabled="disabledList[index]"
        :class="{'btn-disabled':disabledList[index]}" -->
        <button class="circle-btn-buy btn-buy"
          v-if="fielsStatus === 1"
          @click="timeAddShopcart(item.productId, index, item)"
          :ref="`buy_${index}`"
        >{{item.startTime,item.endTime | btnType}}</button>
      </div>
    </div>
    </template>
  </div>
</template>

<script>
import { prefixImg } from '@/tool/index'
// import { getCookie } from '@/config/mUntils'
import { InputNumber } from 'element-ui'
import { mapState, mapActions } from 'vuex'
import { changeProNumber } from '@/service/get-data'
import { eventBus } from '@/tool/events-bus'
import _ from 'lodash'

export default {
  name: 'OctoProduct',
  components: {
    elInputNumber: InputNumber
  },
  props: {
    productList: {
      type: Array || Object,
      default: []
    },
    // 0：未开启， 1： 进行中 2 ：活动结束
    fielsStatus: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      prefixImg,
      dateTime: '',
      startTime: '',
      endTime: '',
      purchaseNum: 0, // 购买的数量
      numList: [],
      flag: true,
      changeflag: true,
      curActDay: '',
      superStockVisi: false // 超过库存的弹窗
    }
  },
  computed: {
    loginStatus () {
      return this.$store.getters.loginStatus
    },
    keyword () {
      return this.$route.query.keyword
    },
    proLen () {
      return this.productList && this.productList.length
    },
    ...mapState({
      limitArr: state => state.shopcart.limitArr,
      shopcartId: state => state.shopcart.shopCartId
    })
  },
  methods: {
    ...mapActions(['fetchCartList']),
    openDetail (item) {
      this.$router.push({name: 'productDetail', params: {commodityID: item.goodsId}, query: {keyword: this.$route.query.keyword}})
    },
    changeNumber (value) {
      const vm = this
      if (value > 20) {
        this.$nextTick(() => {
          vm.$refs['number'].$refs.input.setCurrentValue(5)
        })
      }
    },
    debounceChangeProNum (value, skuIndex, step, objitem) {
      this.debouncePro(value, skuIndex, step, objitem)
    },
    // 添加到购物车
    async addShopcat (proId, skuIndex, objitem) {
      if (this.loginStatus !== 1) return
      if (objitem.lastPersonalLimitNum === 0) {
        this.$message('您已达个人限购数量')
        return
      }
      let purchaseNum = this.numList[skuIndex]
      if (!purchaseNum) {
        return
      }
      let vm = this
      let surplusNum
      let shopcatNum = 0
      if (objitem.personalLimited && objitem.lastPersonalLimitNum > 0) {
        this.limitArr.map((limitItm, limitInd) => {
          if (objitem.productId === limitItm.pid) {
            shopcatNum = limitItm.num
          }
        })
        surplusNum = objitem.lastPersonalLimitNum - shopcatNum
        if (surplusNum <= 0) {
          setTimeout(() => {
            this.numList[skuIndex] = 0
            vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
          }, 200)
          this.$message.error('抱歉,您抢购的商品已达购买上限')
          return
        }
      }
      let res = await changeProNumber(this.shopcartId, proId, '', purchaseNum, 0)
      // _arr['productList'][skuIndex]['number'] = leftNum
      if (res.data.resultCode && res.data.resultCode === 2000) {
        eventBus.$emit('show:pop')
        this.$emit('openActivity')
        this.numList[skuIndex] = 0
        this.$nextTick(() => {
          vm.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
        })
        let endTime = objitem.endTime.split(' ')[1].substr(0, 5)
        this.$alert(`恭喜您，抢购成功~  请在${endTime}前去采购清单结算商品，过期将被移除！`, '抢购成功', {
          showClose: false
        })
        this.fetchCartList() // 更新购物车列表
      } else {
        this.$message.error({
          message: res.data.resultMsg
        })
      }
    },
    timeAddShopcart (proId, skuIndex, objitem) {
      if (this.flag) {
        this.addShopcat(proId, skuIndex, objitem)
      }
      this.flag = false
      setTimeout(() => {
        this.flag = true
      }, 300)
    },
    initDisabledList () {
      let _arr = []
      if (this.productList && this.productList.length > 0) {
        this.productList.map((pro, proIdx) => {
          _arr[proIdx] = false
        })
      }
      this.disabledList = _arr
    },
    showMessage () {
      // curActDay && fielsStatus === 0
      if (!this.curActDay) {
        this.$message(`${this.dateTime[1]}月${this.dateTime[2]}日正式开启，敬请等待`)
      } else if (this.curActDay && this.fielsStatus === 0) {
        this.$message(`${this.startTime}开启，敬请等待`)
      }
    },
    // 时间计算
    // calcOpenedActTime () {
    //   let startTimeParm = this.openedActTime.startTime || 0
    //   let endTimeParm = this.openedActTime.endTime || 0
    //   this.fielsStartTime = startTimeParm
    //   this.fielsEndTime = endTimeParm
    //   this.dateTime = this.fielsStartTime.split(' ')[0].split('-')
    //   this.startTime = this.fielsStartTime.split(' ')[1].substr(0, 5)
    //   this.endTime = this.fielsEndTime.split(' ')[1].substr(0, 5)
    //   let now = new Date()
    //   let month = now.getMonth() + 1
    //   let day = now.getDate()
    //   let today = month + '' + day
    //   let activeDay = `${this.dateTime[1]}${this.dateTime[2]}`
    //   this.curActDay = today === activeDay
    // },
    // 计数器防抖绑定
    debounceStepNum () {
      console.log('nihao')
      this.debouncePro = _.debounce(function (value, skuIndex, step, objitem) {
        if (this.loginStatus !== 1) {
          this.$message('您还未登陆或未审核通过')
          return
        }
        if (objitem.lastPersonalLimitNum === 0) {
          this.$message('您已达个人限购数量')
          return
        }
        if (value === 0) return
        let shopcatNum = 0
        let surplusNum // 去掉购物车数量的剩余可购买数量
        // 如果不存在id请求购物车
        if (!this.shopcartId) {
          this.fetchCartList()
        }
        // 包装盒
        let lastNum = value % step
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        if (lastNum !== 0) {
          this.$message(`您当前选择的商品是${step}件一起采购哦`)
          this.$nextTick(() => {
            this.numList[skuIndex] = leftNum
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
          })
          return
        }
        // 是否超过库存
        if (leftNum > objitem.stock) {
          this.superStockVisi = true
          this.$nextTick(() => {
            this.numList[skuIndex] = objitem.stock
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(objitem.stock)
          })
          return
        }
        // 循环 购物车是否有限购的商品
        if (objitem.personalLimited && objitem.lastPersonalLimitNum > 0) {
          this.limitArr.map((limitItm, limitInd) => {
            if (objitem.productId === limitItm.pid) {
              shopcatNum = limitItm.num
            }
          })
          surplusNum = objitem.lastPersonalLimitNum - shopcatNum
          // 购物存货和限购数量一样
          if (surplusNum === 0) {
            this.$nextTick(() => {
              this.numList[skuIndex] = 0
              this.$refs[`pro_${skuIndex}`][0].setCurrentValue(0)
            })
            this.$message(`抱歉,此商品限购期间每人限购${objitem.personalLimitNum}件,已达此商品的添加上限`)
          // 购买数量大于等于剩余的数量时
          } else if (surplusNum > 0 && leftNum > surplusNum) {
            this.$nextTick(() => {
              this.numList[skuIndex] = surplusNum
              this.$refs[`pro_${skuIndex}`][0].setCurrentValue(surplusNum)
            })
            this.$message('您的选购数量已达上限')
          // 可正常加入购物车
          } else if (surplusNum > 0 && leftNum <= surplusNum) {
            this.$nextTick(() => {
              this.numList[skuIndex] = leftNum
              this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
            })
          }
        } else {
          this.$nextTick(() => {
            this.numList[skuIndex] = leftNum
            this.$refs[`pro_${skuIndex}`][0].setCurrentValue(leftNum)
          })
        }
      }, 300, {leading: true, trailing: false})
    }
  },
  filters: {
    btnType (timeS, timeE) {
      let now = new Date()
      let getTime = now.getTime()
      let startTime = new Date(timeS.replace(/-/g, '/'))
      let endTime = new Date(timeE.replace(/-/g, '/'))
      let time1 = startTime.getTime()
      let time2 = endTime.getTime()
      let month = startTime.getMonth() + 1
      let day = startTime.getDate()
      let hour = String(startTime.getHours())
      let minute = String(startTime.getMinutes())
      if (hour.length < 2) {
        hour = '0' + hour
      }
      if (minute.length < 2) {
        minute = '0' + minute
      }
      if (getTime < time1) {
        // return String(hour) + ':' + String(minute) + '开启'
        if (month !== now.getMonth() + 1 || day !== now.getDate()) {
          month = month + ''
          day = day + ''
          if (month.length < 2) {
            month = '0' + month
          }
          if (day.length < 2) {
            day = '0' + day
          }
          return month + '月' + day + '日正式开启'
        } else {
          return hour + ':' + minute + '开启'
        }
      } else if (getTime >= time1 && getTime < time2) {
        return '立即抢购'
      } else if (getTime >= time2) {
        return String(hour) + ':' + String(minute) + '场已结束'
      }
    }
  },
  mounted () {
    let arr = new Array(this.proLen).fill(0)
    this.numList = JSON.parse(JSON.stringify(arr))
    // this.calcOpenedActTime()
    this.debounceStepNum()
  }
}
</script>

<style lang="scss" scoped>
    .activity-item{
        position: relative;
        width: 392px;
        margin-bottom: 10px;
        padding: 19px 16px;
        font-size: 0;
        display: inline-block;
        background: #fff;
        border-radius: 2px;
      margin-right: 12px;
        -webkit-transition: all 0.2s linear;
        transition: all 0.2s linear;
        overflow: hidden;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
    &:nth-child(3n){
        margin-right: 0;
      }
      .activity-left{
        float: left;
        width: 150px
      }
      .activity-right{
        margin-left: 160px;
      }
      .stock-num{
        display:inline-block;
        padding: 0 10px;
        line-height: 2;
        font-size: 14px;
        background: #413d3d;
        color: #ffffff;
      }
      .preview-img{
        height: 120px;
        width: 120px;
        margin-top: 30px;
        .img{
          width: 100%;
          height: 100%;
          vertical-align: middle
        }
      }
      .pro-name{
        color: #666;
        font-size: 16px;
        line-height: 25px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .pro-type{
        color: #a3a3a3;
        font-size: 12px;
        line-height: 25px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
      }
      .price-box{
        margin-top: 12px;
        padding-bottom: 2px;
      }
      .price{
        margin-bottom: 5px;
        font-size: 0;
      }
      .old{
        color: #bdbdbd;
        font-size: 12px;
        text-decoration: line-through;
        vertical-align: middle;
      }
      .now{
        display: inline-block;
        font-size: 16px;
        padding-right: 3px;
        color: #ff0f34;
        vertical-align: middle;
      }
      .left{
        color: #666;
        font-size: 12px;
      }
      .activity-number{
        margin-bottom: 8px;
        overflow: hidden;
        line-height: 20px;
      }
      .input-num-self-activity{
        float: right;
        width: 88px;
        height: 20px;
        line-height: 20px;
        overflow: hidden;
      }
      .circle-btn-buy{
        text-align: center;
        color: #FF0000;
        border-radius: 2px;
        font-size: 14px;
        line-height: 26px;
        border: 1px solid #FF0000;
        background: transparent;
        margin-bottom: 2px;
        width: 100%;
        cursor: pointer;
      }
      .btn-buy{
        color: #FFF;
        background: #FF0000;
      }
      .btn-disabled{
        color: #666;
        border: 1px solid #666;
        cursor: not-allowed;
      }
      .cannot-buy{
        display:block;
        // width: 100%;
        // height:40px;
        text-align: center;
        color: #ffffff;
        background: #dfdfdf;
        // border-radius: 2px;
        // font-size: 16px;
        // line-height: 40px;
      }
      .sell-out{
        position:absolute;
        left:0;
        top:0;
        bottom: 0;
        right: 0;
        background: rgba(0,0,0,.63);
        z-index: 88;
        .sell-out-img{
          left: 50%;
          transform: translateX(-50%);
          position: absolute;
          top: 20px;
        }
      }
    }
    .activity-item__small{
      width: 220px;
      border: 1px solid #ececec;
      &:nth-child(4n) {
         margin-right: 0;
      }
      &:nth-child(5n){
        margin-right: 10px;
      }
    }
    .btn-yellow-over{
      display: inline-block;
      width:130px;
      height:40px;
      font-size:14px;
      color:rgba(51,51,51,1);
      text-align: center;
      line-height: 40px;
      background:rgba(251,205,59,1);
      border-radius:6px;
    }
    .pro-over-pos{
      position: absolute;
      bottom: 36px;
      left: 50%;
      margin-left: -65px;
      cursor: pointer;
    }
</style>
<style lang="scss">
.input-num-self-activity{
  .el-input__inner{
    height: 20px;
    width: 88px;
    padding-left: 24px!important;
    padding-right: 24px!important;
    font-size: 16px;
    line-height: 20px;
    border-radius: 4px;
    color: #666;
    border: 1px solid #CBCBCB;
    background: transparent!important;
  }
  .el-input-number__decrease{
    border-radius: 4px 0 0 4px;
  }
  .el-input-number__increase{
    border-radius: 0 4px 4px 0;
  }
  .el-input-number__increase, .el-input-number__decrease {
    background: transparent!important;
    width: 24px;
    font-size: 12px
  }
  .el-input-number__increase.is-disabled, .el-input-number__decrease.is-disabled {
    color: #CBCBCB;
    background: transparent!important;
  }
}
</style>

